package one.stand.config;

import lombok.extern.slf4j.Slf4j;
import one.stand.model.essay.EssayVisitorsDataModel;
import one.stand.request.wx.UserTimerModel;
import one.stand.service.BaseService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户访问H5时长定时器
 * @author luoyang
 * @date 2020/5/28 11:11
 */
@Service
@Slf4j
public class UserVisitorsTimerConfig extends BaseService {
    /**
     * 用户访问记录 进入时添加 离开时剔除 string=userId .time = 访问时间
     */
    public static Map<String, UserTimerModel> visitors = new ConcurrentHashMap<>();
    /**
     * 2秒执行一次 检查用户 心跳是否存在，不存在则表示离开
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void build() {
        visitors.forEach((s, userTimerModel) -> {
            //加2秒。判断离开
            if(userTimerModel.getVisitorTime().isBefore(LocalDateTime.now().minusSeconds(2))){
                log.info("用户离开:{}",s);
                EssayVisitorsDataModel visitorsDataModel = this.essayVisitorsDataMapper.queryByOpenId(userTimerModel.getOpenId(),userTimerModel.getDynamicId());
                if(visitorsDataModel != null){
                    //计算访问时长 单位
                    final Long times = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) - userTimerModel.getStartTime().toEpochSecond(ZoneOffset.of("+8"));
                    visitorsDataModel.setSumTimes(visitorsDataModel.getSumTimes() + times.intValue());
                    this.essayVisitorsDataMapper.upateTime(visitorsDataModel);
                }
                visitors.remove(s);
            }
        });
    }

}
